package com.yanqu.road.server.cmd.cross.marriage;

import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.ChatModule;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;

@Cmd(code = Protocol.S_CROSS_MARRIAGE_GROUP_CHAT_LIST_NOTIFY, desc = "跨服联姻分组聊天列表通知")
public class CrossMarriageGroupChatListNotifyCmd implements Command {

	@Override
	public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {
		if(null == packet.getBytes()) {
			return;
		}
		WorldMessageProto.WorldMessageListMsg chatListMsg = WorldMessageProto.WorldMessageListMsg.parseFrom(packet.getBytes());
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(packet.getPlayerId());
		if(null != player){
			List<WorldMessageProto.WorldMessageTempMsg.Builder> forbiddenList = player.getModule(ChatModule.class).getCrossMarriageGroupForbiddenMsg();
			List<WorldMessageProto.WorldMessageTempMsg.Builder> dataList = new ArrayList<>();
			if(null != forbiddenList){
				dataList.addAll(forbiddenList);
			}
			if(null != chatListMsg){
				for(WorldMessageProto.WorldMessageTempMsg tempMsg : chatListMsg.getDataListList()){
					dataList.add(tempMsg.toBuilder());
				}
			}
			dataList.sort((o1, o2) -> (int) (o1.getSendTime() - o2.getSendTime()));
			while (dataList.size() > WorldMessageMgr.MAX_MESSAGE_COUNT){
				dataList.remove(0);
			}
			WorldMessageProto.WorldMessageListMsg.Builder respMsg = WorldMessageProto.WorldMessageListMsg.newBuilder();
			for(WorldMessageProto.WorldMessageTempMsg.Builder msg : dataList){
				respMsg.addDataList(msg);
			}
			player.sendPacket(Protocol.U_CROSS_MARRIAGE_GROUP_CHAT_LIST, respMsg);
		}
	}
}
